package com.example.weather_forecast;

package com.example.weather_forecast;

import android.app.Application;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import java.util.List;

public class CityViewModel extends AndroidViewModel {

    private AppDatabase db;
    private CityDao cityDao;
    private MutableLiveData<List<City>> cities = new MutableLiveData<>();

    public CityViewModel(Application application) {
        super(application);
        db = AppDatabase.getDatabase(application);
        cityDao = db.cityDao();
    }

    public LiveData<List<City>> getCities() {
        new Thread(() -> {
            cities.postValue(cityDao.getAllCities());
        }).start();
        return cities;
    }

    public void addCity(City city) {
        new Thread(() -> {
            cityDao.insert(city);
            cities.postValue(cityDao.getAllCities());
        }).start();
    }

    public void removeCity(City city) {
        new Thread(() -> {
            cityDao.delete(city);
            cities.postValue(cityDao.getAllCities());
        }).start();
    }

    public void searchCity(String cityName) {
        new Thread(() -> {
            // 使用模糊搜索功能
            List<City> cityList = cityDao.searchCities("%" + cityName + "%");
            cities.postValue(cityList.isEmpty() ? List.of() : cityList);  // 若无结果则返回空列表
        }).start();
    }
}

